package server

import (
	"encoding/json"
	"github.com/godruoyi/go-snowflake"
	"golang.org/x/net/context"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/config"
	fans_group2 "longmen/server/internal/rpc/tencentim/fans_group"
	"longmen/server/internal/rpc/tencentim/imsdk"
	"longmen/server/internal/rpc/tencentim/messages"
	room_event2 "longmen/server/internal/rpc/tencentim/room_event"
	"longmen/server/internal/rpc/tencentim/utils"
	"longmen/server/pkg/common/sdk/tx"
	pb "longmen/server/pkg/protobuf"
	"strconv"
)

/**
 * @Author admin
 * @Description //
 * @version: v1.8.0
 * @Date 15:04 2022/8/17
 * @Param
 * @return
 **/
func (s *TencentIM) GetUserSig(ctx context.Context, req *pb.UserSigReq) (*pb.UserSigResp, error) {
	ret := &pb.UserSigResp{}
	expireTime := global.GetTenCentAccExpireTime()
	if len(req.Id) == 0 { //未登陆的用户
		snowid, _ := snowflake.NextID()
		req.Id = strconv.FormatUint(snowid, 10)
		expireTime = global.GetTenCentUnrealAccExpireTime()
	}
	//global.Log.Debugf("uid:%v,当前时间:%v，过期时间:%v,apid:%v,key:%v", req.Id, time.Now().Unix(), expireTime, global.GetTenCentAppId(), global.GetTenCentSecretKey())
	sig, err := tx.GenUserSig(global.GetTenCentAppId(), global.GetTenCentSecretKey(), req.Id, expireTime)
	if err == nil {
		ret.Id = req.Id
		ret.Sig = sig
		global.Log.Debugf("GetUserSig appid:%v,key:%v,uid:%v,sig:%v,expireTime:%v", global.GetTenCentAppId(), global.GetTenCentSecretKey(), req.Id, sig, expireTime)
	} else {
		global.Log.Errorf("GetUserSig err:%v", err)
	}

	return ret, nil

}

// Callback 腾讯回调方法，所有的业务逻辑处理都在这里
func (s *TencentIM) Callback(ctx context.Context, req *pb.CallbackReq) (*pb.CallbackResp, error) {
	switch req.GetCallbackCommand() {
	case config.C2CBeforeMsg:
		// 单聊消息
		allMsg := req.GetMsgBody()
		for _, msg := range allMsg {
			switch msg.MsgType {
			case imsdk.TIM_MSG_TYPE_CUSTOM: // 其他类型
				bytes := []byte(msg.MsgContent.Data)
				if len(msg.MsgContent.Data) == 0 {
					bytes = []byte(msg.MsgContent.Text)
				}
				incomeMsg := messages.IncomingMessage{}
				err := json.Unmarshal(bytes, &incomeMsg)
				if err != nil || incomeMsg.Type == nil {
					return utils.CallbackFailResp(nil, "消息不能识别或缺少type"), err
				}
				switch *incomeMsg.Type {

				case fans_group2.C2CFansGroupHistory:
					return fans_group2.C2CHandler(req, &incomeMsg, bytes)

				default:
					return room_event2.AvChatC2CHandler(req, &incomeMsg, bytes)
				}

			}
		}
	case config.StateChange:
		//global.Log.Debugf("回调command: 在线状态回调:%+v", req)
		return room_event2.CallBackHandlingLogout(req)
	case config.QuitRoom:
		global.Log.Debugf("回调command: 用户退出直播群，！！！！:%+v", req)
	}

	switch req.Type {
	// 直播群
	case imsdk.AvChatGroup:
		// 直播群处理方法
		return room_event2.AvChatGroupHandler(req)
	// 粉丝群
	case imsdk.PrivateGroup:
		// 粉丝群处理方法
		return fans_group2.FansGroupHandler(ctx, req)
	}

	return utils.CallbackOkResp(""), nil
}
